<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body ng-app="shopping" ng-controller="indexController">
<input type="text" ng-model="id">
<button ng-click="queryById()">加载数据</button>
<button ng-click="deleteById()">加载数据</button>
<br>
<input type="text" ng-model="name">
<button ng-click="loadByName()">加载Users</button>
<br>
<hr>
<input type="text" ng-model="user.id">
<input type="text" ng-model="user.username">
<button ng-click="addUser()">save方法</button>
<hr>
<input type="text" ng-model="user.id" ng-init="user.id=1001">
<input type="text" ng-model="user.username">
<button ng-click="updateUser()">put方法</button>

<script src="/scripts/plugins/angularjs/angular.min.js"></script>
<script src="/scripts/plugins/angularjs/angular-resource.min.js"></script>
<script>
    var shopping = angular.module("shopping", ["ngResource"]);

    //定义服务层
    shopping.service("userServices", function ($resource) {
        //创建一个资源对象
        let UserServices = $resource('http://localhost:8080/user/:id', {id: '@id'});
        this.loadUserById = function (id) {
            return UserServices.get({id: id});
        }

        this.loadUsersByName=function(name){
            return $resource('http://localhost:8080/user/like/:name').query({name:name});
        }

        this.deleteById=function(id){
            return UserServices.delete({id:id});
        }

        this.insertUser=function(entity){
           return $resource('http://localhost:8080/user').save({},entity);
        }

        this.updateUser=function(entity){
            return $resource("http://localhost:8080/user",null,{
                put:{method:'PUT'}
            }).put({},entity);
        }
    });

    //定义控制器
    shopping.controller("indexController", function ($scope, userServices) {
        $scope.queryById = function () {
            userServices.loadUserById($scope.id).$promise.then(function success(response) {
                console.log(response);
            });
        }

        $scope.loadByName=function(){
        userServices.loadUsersByName($scope.name).$promise.then(function success(response) {
            console.log(response);
        });
    }

        $scope.deleteById = function () {
            userServices.deleteById($scope.id).$promise.then(function success(response) {
                console.log(response);
            });
        }

        $scope.addUser=function(){
            userServices.insertUser($scope.user).$promise.then(function success(response) {
                console.log(response);
            });
        }

        $scope.updateUser=function(){
            userServices.updateUser($scope.user).$promise.then(function success(response) {
                console.log(response);
            });
        }
    });
</script>
</body>
</html>